#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "tcpserved.hpp"
#include "HttpServer.hpp"
#include "HttProtocol.hpp"

using namespace TcpserverModule;
// const std::string Sep = "\r\n";
// const std::string BlankLine = Sep;

using http_handler_t = std::function<void (HttpRequest&, HttpResponse&)>;

class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }

    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }

    bool SafeCheck(std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
                          { return this->HanderHttpRequest(sockfd, client); });
        _tsvr->Loop();
    }

    // 这就是处理HTTP的入口
    bool HanderHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(DEBUG, "HttpServer: get a new client: sockfd is %d, info is %s\n", sockfd->Fd(), client.AddrStr().c_str());
        std::string http_request;
        sockfd->Recv(&http_request);

        // 反序列化
        HttpRequest req;
        req.Deserialize(http_request);
        // req.Print();
        // std::cout << "用户想要: " << req.Uri() << std::endl;
        // req.GetContent();

        // 序列化，构建应答
        HttpResponse resp;
        // 请求应该被分成两类  1. 请求一般的静态资源   2. 提交参数，携带参数，需要进行交互设置
        if (req.IsHasArgs())
        {
            // 提交参数，携带参数，需要进行交互设置
            std::string service = req.Path();
            if(SafeCheck(service))
                _route[req.Path()](req, resp);
            else
                resp.Build(req);    
        }
        else
        {
            resp.Build(req);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;

        //         std::cout << http_request;
        //         // 读取请求，对请求进行处理 --> 是对文本进行处理

        //         std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

        //         std::string body = R"(
        // <!DOCTYPE html>
        // <html lang="zh-CN">
        // <head>
        //     <meta charset="UTF-8">
        //     <meta name="viewport" content="width=device-width, initial-scale=1.0">
        //     <title>Hello World</title>
        // </head>
        // <body>
        //     <h1>Hello, World!</h1>
        // </body>
        // </html>
        // )";
        //         std::string http_response = status_line + body;

        //         sockfd->Send(http_response);
        return true;
    }

    ~HttpServer()
    {
    }

private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route; // 功能路由
};